<?php
namespace app\api\controller\admin;



class User extends AdminApi {
	public $authGroup;// 分组ID


	public function _initialize(){
		$this->Table='user';
		$this->Prefix='user_';
		$this->Order='user_createtime desc';
		$this->PrimaryKey='user_id';
		$this->SearchField='user_name';
		$this->CreateDate=['user_createtime'];
		$this->IndexField='user_id,user_is_open,user_headpic,user_createtime,user_name,ag_title';
		$this->Join=[
			['auth_group_menu b','a.user_id=b.agm_uid'],
			['auth_group c','b.agm_group_id=c.ag_id'],
		];
		parent::_initialize(); // TODO: Change the autogenerated stub
	}

	//改变用户状态
	public function changeStatus(){
		$res=db($this->Table)->where($this->PrimaryKey,input('post.id'))->update(['user_is_open'=>input('post.status')]);
		if($res){
			return $this->jsuccess();
		}return $this->jerror();
	}

	protected function beforeSave(&$data){
		//检查账号是否存在
		if($res=db('user')->where('user_name',$data['user_name'])->find()){
			return $this->jerror('账号名已存在');
		}
		//填充数据
		$data['user_salt']=rand_str(4);
		$data['user_pwd'] = md5_salt($data['user_pwd'], $data['user_salt']);
		//去除无用数据
		$this->authGroup=$data['user_ag_id'];
		unset($data['user_ag_id']);
		return true;
	}

	protected function afterSave($id, $data){
		db('auth_group_menu')->insert(['agm_uid'=>$id,'agm_group_id'=>$this->authGroup]);
		return true;
	}

	protected function beforeUpdate(&$data,$id,$pk){
		//取得salt值
		$user_salt=db('user')->where('user_id',$id)->value('user_salt');
		$data['user_pwd'] = md5_salt($data['user_pwd'],$user_salt);
		//去除没有必要的值
		$this->authGroup=$data['user_ag_id'];
		unset($data['user_name'],$data['user_ag_id']);
		return true;
	}

	protected function afterUpdate(&$data, $id, $pk){
		db('auth_group_menu')->where('agm_uid',$id)->update(['agm_group_id'=>$this->authGroup]);
		return true;
	}


	protected function beforeRead(&$id, &$pk){
		$this->Join=[
			['auth_group_menu b','a.user_id=b.agm_uid'],
			['auth_group c','b.agm_group_id=c.ag_id']
		];
		$this->FindField='user_id,user_name,user_pwd,user_headpic,ag_id';
		return true;
	}
}